package adminservice

import (
	"yunj/pkg/yunj/app/model"

	"github.com/gin-gonic/gin"
)

// 设置当前请求权限
func SetRequestAuth(ctx *gin.Context, adminAuth *model.AdminAuth) bool {
	if adminAuth != nil && adminAuth.Key != "" {
		ctx.Set("adminAuth", adminAuth)
		return true
	}
	return false
}

// 获取当前请求权限
func GetRequestAuth(ctx *gin.Context) (adminAuth *model.AdminAuth) {
	value, exists := ctx.Get("adminAuth")
	if !exists {
		return
	}
	if auth, ok := value.(*model.AdminAuth); ok {
		adminAuth = auth
	}
	return
}

// 设置当前登录成员
func SetLoginMember(ctx *gin.Context, adminMember *model.AdminMember) bool {
	if adminMember != nil && adminMember.Id > 0 {
		ctx.Set("adminMember", adminMember)
		return true
	}
	return false
}

// 获取当前登录成员
func GetLoginMember(ctx *gin.Context) (adminMember *model.AdminMember) {
	value, exists := ctx.Get("adminMember")
	if !exists {
		return
	}
	if member, ok := value.(*model.AdminMember); ok {
		adminMember = member
	}
	return
}

// 获取当前登录成员id
func GetLoginMemberId(ctx *gin.Context) (id uint64) {
	member := GetLoginMember(ctx)
	if member != nil && member.Id > 0 {
		id = member.Id
	}
	return
}

// 校验权限
func CheckAuth(ctx *gin.Context, authKey string) (res bool) {
	if authKey == "" {
		return true
	}
	adminMember := GetLoginMember(ctx)
	if adminMember == nil {
		return
	}
	// 判断是否拥有所有权限
	if adminMember.IsHasAllAuth() {
		return true
	}
	// 判断角色权限
	roles := adminMember.GetOwnRoles()
	if len(roles) <= 0 {
		return
	}
	roleAuthKeyMap := adminMember.GetOwnRoleAuthKeyMap()
	if _, exists := roleAuthKeyMap[authKey]; !exists {
		return
	}
	res = true
	return
}
